const instance = require("../utils/instance");
const { useAgent } = require("../hooks");
const { v4 } = require("uuid");
const axios = require("axios");
const fs = require("fs");

const baiduApi = {
  // 获取二维码
  getLidTokenText() {
    return instance({
      url: "https://chat.baidu.com/search?extParams=%7B%22enter_type%22%3A%22chat_url%22%7D&isShowHello=1",
      method: "get",
      headers: {
        "user-agent": useAgent(),
      },
    });
  },
  // 获取二维码
  getQrcode() {
    return instance({
      url: "https://passport.baidu.com/v2/api/getqrcode?lp=pc&qrloginfrom=pc",
      method: "get",
      headers: {
        referer: "https://image.baidu.com/",
        "user-agent": useAgent(),
      },
    });
  },
  // 获取二维码状态
  getUnicast({ params }) {
    const newParams = Object.assign(
      {
        tpl: "im",
        _sdkFrom: 1,
        apiver: 3,
      },
      params
    );
    return instance({
      url: "https://passport.baidu.com/channel/unicast",
      method: "get",
      params: newParams,
      headers: {
        referer: "https://image.baidu.com/",
        "user-agent": useAgent(),
      },
    });
  },
  // 登录信息
  qrbdusslogin(params) {
    const v = Date.now();
    const newParams = Object.assign(
      {
        v: v,
        u: "https://image.baidu.com/front/aigc",
        loginVersion: "v5",
        qrcode: 1,
        tpl: "im",
        maskId: "",
        fileId: "",
        apiver: "v3",
        tt: v,
        traceid: "",
        time: Math.floor(v / 1000),
        alg: "v3",
        sig: "MmgrL3R2am14NTNhNWpzYWZ3eEtJWFJKbktsVmRLcmRRZ1ZIY3NNQmc3byt6RzNDb3dVM2pRT0hhWG85OGtwWg",
        elapsed: 7,
        shaOne: "006ff317c22a56d918f12d19305fdb2290df99f2",
        rinfo: { fuid: v4().replace(/-/g, "") },
        callback: "bd__cbs__gob8sd",
      },
      params
    );
    return instance({
      url: "https://passport.baidu.com/v3/login/main/qrbdusslogin",
      method: "get",
      params: newParams,
      headers: {
        referer: "https://image.baidu.com/",
        "user-agent": useAgent(),
      },
    });
  },
  // ai创建chatToken
  checkquerydanger({ cookie, params }) {
    const newParams = Object.assign(
      {
        // query:"",
        sge_lid: "",
        token: "",
      },
      params
    );
    return instance({
      url: "https://chat.baidu.com/aichat/api/checkquerydanger",
      method: "get",
      params: newParams,
      headers: {
        cookie,
        referer:
          "https://chat.baidu.com/search?extParams=%7B%22enter_type%22%3A%22chat_url%22%7D&isShowHello=1",
        "user-agent": useAgent(),
      },
    });
  },
  // ai返回聊天
  conversation({ cookie, data }, cb, endFn) {
    return new Promise((resolve) => {
      axios({
        method: "post",
        url: "https://chat.baidu.com/aichat/api/conversation",
        data: data,
        responseType: "stream",
        headers: {
          cookie,
          origin: "https://chat.baidu.com",
          referer:
            "https://chat.baidu.com/search?extParams=%7B%22enter_type%22%3A%22chat_url%22%7D&isShowHello=1",
          "user-agent": useAgent(),
        },
      })
        .then((response) => {
          var result = [];
          var resultData = "";

          response.data.on("data", (chunk) => {
            var str = chunk.toString().trim();
            if (!str) return;
            if (str.indexOf("event:basedata") > -1) return;
            if (str.indexOf("event:ping") > -1) return;
            resultData += str;
            if (
              resultData.includes("event:message") &&
              str.substring(str.length - 1) === "}"
            ) {
              const d = resultData.split("\n");

              for (var i = 0; i < d.length; i++) {
                if (d[i].indexOf("data:{") > -1) {
                  const k = d[i].replace("data:", "");
                  cb(k);
                  // console.log(k);
                  const ev = handleEvent(k);
                  ev && result.push(ev);
                }
              }
              resultData = "";
            }
          });
          response.data.on("end", () => {
            var newStr = "";
            for (var i = 0; i < result.length; i++) {
              const k = result[i];
              if (
                k &&
                k.data &&
                k.data.message.content &&
                k.data.message.content.generator &&
                k.data.message.content.generator.data
              ) {
                newStr +=
                  k.data.message.content.generator.data.value ||
                  k.data.message.content.generator.data.content ||
                  "";
              }
            }
            console.log(newStr);
            newStr = extractVariables(newStr);
            console.log(newStr, "newStr...");
            endFn(newStr);
            // resolve({ code: 200, data: newStr, message: "success" });
            console.log("Stream has ended.");
          });
        })
        .catch((err) => {
          resolve({ code: 500, data: "", message: err.message });
        });
    });
  },
};

function handleEvent(eventString) {
  // 解析并处理事件字符串
  try {
    return JSON.parse(eventString);
  } catch (err) {
    return "";
  }
}

function extractVariables(code) {
  const result = {};

  // 匹配 goldSentence
  const goldSentenceMatch = code.match(
    /(const|let|var)\s+goldSentence\s*=\s*\[([\s\S]*?)\];/
  );
  if (goldSentenceMatch) {
    result.goldSentence = eval(`[${goldSentenceMatch[2]}]`);
  }

  // 匹配 hotTitle
  const hotTitleMatch = code.match(
    /(const|let|var)\s+hotTitle\s*=\s*"([^"]*)";/
  );
  if (hotTitleMatch) {
    result.hotTitle = hotTitleMatch[2];
  }

  // 匹配 digest
  const digestMatch = code.match(/(const|let|var)\s+digest\s*=\s*"([^"]*)";/);
  if (digestMatch) {
    result.digest = digestMatch[2];
  }

  // 匹配 outputList
  const outputListMatch = code.match(
    /(const|let|var)\s+outputList\s*=\s*\[([\s\S]*?)\];/
  );
  if (outputListMatch) {
    result.outputList = eval(`[${outputListMatch[2]}]`);
  }

  // 匹配 cover
  const coverMatch = code.match(/(const|let|var)\s+cover\s*=\s*"([^"]*)";/);
  if (coverMatch) {
    result.cover = coverMatch[2];
  }

  return result;
}

module.exports = baiduApi;
